/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.swing.DefaultListModel;
import javax.swing.JList;

/**
 *
 * @author alan
 */
public class ThreadMBeanServer implements Runnable {

    private MBeanServerConnection JMXSC;
    private MBeanServer mbServer;
    private DefaultListModel modeloLista;
    private String ip;
    private String nome;
    private String os;
    private JList jlPCInstrumentados;

    public ThreadMBeanServer(MBeanServer mbServer, DefaultListModel modeloLista) {
    }

    public ThreadMBeanServer(MBeanServer mbServer, DefaultListModel modeloLista, JList jlPCInstrumentados) {
        this.mbServer = mbServer;
        this.modeloLista = modeloLista;
        this.jlPCInstrumentados = jlPCInstrumentados;
    }

    @Override
    public void run() {
        while (true) {
            try {
                JMXSC = mbServer;
                Set<ObjectInstance> listaObject = JMXSC.queryMBeans(new ObjectName("tcc:*"), null);
                modeloLista.removeAllElements();
                jlPCInstrumentados.validate();
                for (ObjectInstance obj : listaObject) {
                    ip = obj.getObjectName().getKeyProperty("ip");
                    nome = obj.getObjectName().getKeyProperty("nome");
                    os = obj.getObjectName().getKeyProperty("type");
                    if (ip != null || nome != null) {
                        Computer computer = new Computer(ip, nome, os);
                        modeloLista.addElement(computer);
                    }
                }

               Thread.sleep(2000);
            } catch (InterruptedException ex) {
                Logger.getLogger(ThreadMBeanServer.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(ThreadMBeanServer.class.getName()).log(Level.SEVERE, null, ex);
            } catch (MalformedObjectNameException ex) {
                Logger.getLogger(ThreadMBeanServer.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NullPointerException ex) {
                Logger.getLogger(ThreadMBeanServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
